package com.zzx.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.business.service.ITbFileVersionsService;
import com.zzx.business.vo.TbFileVersionsVo;
import com.zzx.common.core.page.TableDataInfo;
import com.zzx.common.utils.PageUtils;
import com.zzx.business.domain.TbFiles;
import com.zzx.business.vo.TbFilesVo;
import com.zzx.business.mapper.TbFilesMapper;
import com.zzx.business.service.ITbFilesService;
import com.zzx.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文件列表Service业务层处理
 *
 * @author Zzx
 * @date 2025-05-23
 */
@Service
public class TbFilesServiceImpl extends ServiceImpl<TbFilesMapper, TbFiles> implements ITbFilesService {

    @Autowired
    private ITbFileVersionsService fileVersionsService;

    @Override
    public TableDataInfo<TbFilesVo> queryList(TbFilesVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<TbFilesVo> queryAll(TbFilesVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public TbFilesVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Transactional
    @Override
    public boolean saveFile(TbFilesVo entity) {

        String filePath = entity.getFilePath();
        this.save(entity);

        TbFileVersionsVo fileVersionsVo = new TbFileVersionsVo();
        fileVersionsVo.setFileId(entity.getId());
        fileVersionsVo.setPath(filePath);
        fileVersionsVo.setChangeLog(entity.getRemark());

        fileVersionsService.save(fileVersionsVo);

        return true;
    }

    @Transactional
    @Override
    public boolean updateFile(TbFilesVo entity) {
        String filePath = entity.getFilePath();
        if(StringUtils.isNotBlank(filePath)){
            Long version = entity.getVersion();
            version += 1;
            entity.setVersion(version);
            TbFileVersionsVo fileVersionsVo = new TbFileVersionsVo();
            fileVersionsVo.setFileId(entity.getId());
            fileVersionsVo.setPath(filePath);
            fileVersionsVo.setVersionNumber(version);
            fileVersionsVo.setChangeLog(entity.getRemark());
            fileVersionsService.save(fileVersionsVo);
        }
        this.updateById(entity);
        return true;
    }
}
